const { Admin } = require("../models/adminModel.js");
const time = require("moment");
const { moveFiles, removeFiles } = require("../utils/upload.js");
const jwt = require("jsonwebtoken")
const { TOKEN_KEY } = require("../utils/consts.js");
// import imagesModel from '../models/imagesModel.js';
//adminlogin
async function adminlogin(req, res, next) {
    const { adminname, password } = req.body;
    console.log(req.body);
    const data = await Admin.find({ adminname:adminname,password: password });
    console.log("用户登陆的数据",data);
    if (data.length > 0) {
        const role = data[0].userGroup;
        const _id=data[0]._id;
        const token = jwt.sign(
            {adminname,
            role,
            _id,
            expiresIn: 60 * 60 },
            TOKEN_KEY,
        );
        res.send({
            message: "登陆成功", status: 1,
            data: {
                userInfo: { data, role },
                token,
            }
        })
    } else {
        res.send({ message: "登陆失败", status: 0, type: "LOGIN_FILED", },)
    }
}
//register
async function adminregister(req, res, next) {
    const { adminname, password } = req.body;
    const isrepet = await Admin.find({ adminname });
    if (isrepet.length < 0) {
        res.send({ message: "注册成功", status: 1, data, token },)
    } else {
        res.send({ message: "用户名重复", status: 0, type: "REGISTER_FILED", },)
    }
}
//获取所有数据
async function showadmin(req, res, next) {
    //get
    const { type = "adminname", value = "", pageSize = 10, currentPage = 1 } = req.query;
    const totalNum = await Admin.countDocuments();
    const totalPages = Math.ceil(totalNum / pageSize);
    const data = await Admin
        .find({ [type]: { $regex: value, $options: "$i" } })
        .limit(pageSize - 0)
        .skip((currentPage - 1) * pageSize)
        .populate({path:"imagesId"});
        console.log("获取所有数据",data);
    if (data) {
        res.send({
            message: "列表数据获取成功", status: 1,
            data:{
                pageSize, totalNum, totalPages, currentPage, data,
            } 
        })
    } else {
        res.send({
            status: 0,
            message: "数据获取失败"
        })
    }
}
//新增
async function addadmin(req, res, next) {
    console.log(req.body, "获取页面新增的数据");
    const { adminname, password,userGroup,imgname="" } = req.body;
    const isrepet = await Admin.find({ adminname });
    // console.log("2222222",imgname.file.name);
    if (isrepet.length > 0) {
        res.send({ message: "用户名重复", status: 0, type: "addadmin_FILED", },)
    } else {
        // if(imgname.file.name){
        //     moveFiles({
        //         fromPath: './public/temp/',
        //         toPath: "./public/images/",
        //         filename: imgname.file.name,
        //     });
        //     removeFiles('../public/temp/')
        // }
        const data = await Admin.create({ adminname:adminname, password: password,userGroup:userGroup,state:"生效中", })
        res.send({ message: "新增成功", status: 1, data,},)
    }
}

//删除 
async function deleteadmin(req, res, next) {
    console.log("有没有要删除的idreq.query",req.query);
    const { id } = req.query;
    const isid = await Admin.find({ _id: id });
    console.log("有没有要删除的id",id);
    if (isid) {
        let data1 = await Admin.deleteOne({ _id:id });
        if (data1.deletedCount == 1) {
            let data = await Admin.find();
            res.send({
                message: "删除成功",
                status: 1,
                data: data,
            })
        }
    } else {
        res.send({
            message: "id获取失败",
            status: 0,
        })
    }
}
// 获取要修改的数据的id
async function getadminid(req, res, next) {
    const {id} = req.query;
    console.log("获取要修改的数据的id",id);
    const stuid = await Admin.find({ _id: id })
    if (stuid) {
        res.send({
            message: "数据id获取成功",
            status: 1,
            data: stuid,
        })
    } else {
        res.send({
            status: 0,
            message: "数据id获取失败",
        })
    }

}
//修改 
async function updateadmin(req, res, next) {
    try {
        console.log("修改呀",req.body);
        const {  adminname,password,state,userGroup,imgname="" } = req.body;
        const stuid = await Admin.find({ adminname: adminname });
        const thestu = await Admin.updateOne({adminname: adminname}, {  password:password,state:state,userGroup:userGroup, });
        console.log(thestu, "修改结果");
        if (thestu.nModified == 1) {
            let data = await Admin.find();
            // if({...imgname.file.name}){
            //     moveFiles({
            //         fromPath: './public/temp/',
            //         toPath: "./public/images/",
            //         filename: imgname.file.name,
            //     });
            //     removeFiles('./public/temp/')
            // }
            res.send({
                message: "修改成功",
                status: 1,
                data: data,
            })
        } else {
            res.send({
                status: 0,
                message: "修改失败",
            })
        }

    } catch (error) {
        console.log('修改失败', error);
        res.send({
            status: 0,
            message: '修改失败'
        })
    }
}
module.exports = { adminlogin, adminregister, showadmin, addadmin, deleteadmin, getadminid, updateadmin };